package com.eupmt.lab3.persistence.ibatis.dao;

import com.eupmt.lab3.domain.Article;
import com.eupmt.lab3.exceptions.ArticleJaExisteixException;
import com.eupmt.lab3.persistence.ibatis.PersistenceManager;
import com.eupmt.lab3.persistence.ibatis.dao.ibator.IbatorArticleDAOImpl;
import static com.eupmt.lab3.utils.Constants.*;
import com.eupmt.lab3.utils.Log;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException;
import java.sql.SQLException;

public class ArticleDAOImpl extends IbatorArticleDAOImpl implements ArticleDAO {

    //Atributs
    private SqlMapClient sqlMapClient;
    private Log log = null;

    //Constructors
    public ArticleDAOImpl() {
        super();
        sqlMapClient = PersistenceManager.getInstance().getSqlMapClient();
        log = new Log();
    }

    public void deleteArticle(Article art) throws Exception {
        sqlMapClient.delete("article.deleteIdArticle", art);
    }

    public void saveArticle(Article a) throws Exception {
        //TODO Controlar Exceptions

        log.infoLog("Article a fer save: " + a.getIdarticle());

        if (a.getIdarticle() == UNDEFINED) {
            insertArticle(a);
        } else {
            updateArticle(a);
        }
    }

    public void updateArticle(Article a) throws Exception {
        sqlMapClient.update("article.updateByIdArticle", a);
    }

    public void insertArticle(Article a) throws Exception {
        try {
            sqlMapClient.insert("article.insert", a);
        } catch (SQLException sqle) {
            if (sqle.getErrorCode() == ARTICLE_JA_EXISTEIX) {
                throw new ArticleJaExisteixException(sqle.getMessage());
            }
        }
    }

    public Article getArticleById(int idArticle) throws Exception {
        Article a1 = new Article();
        a1.setIdarticle(idArticle);
        Article a2 = null;

        try {
            a2 = (Article) sqlMapClient.queryForObject("article.selectByIdArticle", a1);

        } catch (MySQLIntegrityConstraintViolationException sqle) {
            log.infoLog("SQLErrorCode: " + sqle.getErrorCode());
        }
        return a2;
    }
}
